//
//  KABMallProDetailVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/21.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABMallProDetailVC.h"
#import "KABMallSurOrdFooterHFView.h"
#import "WXApi.h"
#import "XDAFNetworking.h"
#import "ApiManager.h"
#import "GlobalHeader.h"
#import "KABModel.h"
#import "MBProgressHUD+XDPrompt.h"
#import "KABMallSureOrderVC.h"
#import "KABMallBuyVC.h"
#import "KABModel.h"
#import "GGBannerView.h"
#import "KABCosDetComHeaderHFView.h"
#import "KABCosDetailTCell.h"
#import "KABMallProDetOwnerTCell.h"
#import <YYWebImage.h>
#import "KABMallShopcartVC.h"
#import "UIButton+EdgeInsets.h"
#import "KABMallMyShopVC.h"
#import "KSPhotoBrowser.h"
#import "KABRCIMChatVC.h"
#import "KABHomepageVC.h"

@interface KABMallProDetailVC ()<UITableViewDelegate, UITableViewDataSource, KABCosDetailTCellDelegate, GGBannerViewDelegate>

@property (strong, nonatomic) IBOutlet UIView *headerBgView;
@property (weak, nonatomic) IBOutlet GGBannerView *hGGBannerView;
@property (weak, nonatomic) IBOutlet UILabel *hPriceLabel;
@property (weak, nonatomic) IBOutlet UILabel *hFeightLabel;

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *cmrServiceBtn;
@property (weak, nonatomic) IBOutlet UIButton *shopBtn;
@property (weak, nonatomic) IBOutlet UIButton *proColBtn;
@property (weak, nonatomic) IBOutlet UIButton *joinCartBtn;
@property (weak, nonatomic) IBOutlet UIButton *buyBtn;

@property (strong, nonatomic) KABMallProDetail *productModel;

@end

static NSString *const kShopOwnerCellId = @"KABMallProDetOwnerTCell";
static NSString *const kReuseCellId = @"KABCosDetailTCell";
static NSString *const kHeaderViewId = @"KABCosDetComHeaderHFView";
//static NSString *const kFooterViewId = @"KABMallSurOrdFooterHFView";

@implementation KABMallProDetailVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
//    self.navigationItem.title = @"商品详情";
    self.navigationItem.title = self.proItem.name;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"mall_shop_cart"] style:UIBarButtonItemStylePlain target:self action:@selector(shopCartBarBtnTapped:)];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)initSubViews {
    //    self.automaticallyAdjustsScrollViewInsets = NO;
    //
    //    self.tableView.contentInset = UIEdgeInsetsMake(-64 * 2.0, 0, 49.0, 0);
    //    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(64, 0, 49.0, 0);
    
    self.hGGBannerView.delegate = self;
    CGFloat width = CGRectGetWidth([UIScreen mainScreen].bounds);
    CGFloat height = width * 225.0 / 375.0 + 56;
    self.headerBgView.frame = CGRectMake(0, 0, width, height);
    self.tableView.tableHeaderView = self.headerBgView;
    //    self.tableView.tableFooterView = self.footerBgView;
    
    UINib *headerNib = [UINib nibWithNibName:kHeaderViewId bundle:nil];
    [self.tableView registerNib:headerNib forHeaderFooterViewReuseIdentifier:kHeaderViewId];
    UINib *cellNib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:cellNib forCellReuseIdentifier:kReuseCellId];
    UINib *ownerCellNib = [UINib nibWithNibName:kShopOwnerCellId bundle:nil];
    [self.tableView registerNib:ownerCellNib forCellReuseIdentifier:kShopOwnerCellId];
//    UINib *footerNib = [UINib nibWithNibName:kFooterViewId bundle:nil];
//    [self.tableView registerNib:footerNib forHeaderFooterViewReuseIdentifier:kFooterViewId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 400.0;
    self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedSectionHeaderHeight = 48.0;
    self.tableView.sectionFooterHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedSectionFooterHeight = 108.0;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.cmrServiceBtn layoutButtonWithEdgeInsetsStyle:ButtonEdgeInsetsStyleImageTop imageTitlespace:2.0];
    [self.shopBtn layoutButtonWithEdgeInsetsStyle:ButtonEdgeInsetsStyleImageTop imageTitlespace:2.0];
    [self.proColBtn layoutButtonWithEdgeInsetsStyle:ButtonEdgeInsetsStyleImageTop imageTitlespace:2.0];
    [self.cmrServiceBtn addTarget:self action:@selector(cmrServiceBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.shopBtn addTarget:self action:@selector(shopBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.proColBtn addTarget:self action:@selector(proColBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.joinCartBtn addTarget:self action:@selector(joinCartBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.buyBtn addTarget:self action:@selector(buyBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    // 请求网络
    [self requestProductDetail];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }
    
    return self.productModel.introduce_image_list.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        KABMallProDetOwnerTCell *cell = [tableView dequeueReusableCellWithIdentifier:kShopOwnerCellId forIndexPath:indexPath];
        [cell configViewWithProDetail:self.productModel];
        return cell;
    }
    
    KABCosDetailTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    [cell configViewWithProDetImgItem:self.productModel.introduce_image_list[indexPath.row]];
    cell.delegate = self;
    return cell;
}

#pragma mark - UITableViewDelegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    KABCosDetComHeaderHFView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kHeaderViewId];
    [view configViewWithProDetail:self.productModel section:section];
    return view;
}

//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
//    KABMallSurOrdFooterHFView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kFooterViewId];
//    return view;
//}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
//    return 0.1;
//}
//
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 6.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {   // 跳转到个人主页去
        KABHomepageVC *hpVC = [[KABHomepageVC alloc] init];
        hpVC.user_id = self.productModel.shop_owner_id;
        hpVC.user_name = self.productModel.shop_owner;
        [self showViewController:hpVC sender:nil];
    }
}

#pragma mark - KABCosDetailTCellDelegate
- (void)kABCosDetailTCell:(KABCosDetailTCell *)cell imgViewDownload:(UIImageView *)imgView {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    //    NSLog(@"加载图片的位置%@, cell = %@", indexPath, cell);
    if (indexPath) {
         [self.tableView reloadData];
        // 用下面的方式，会导致界面跳动比较大
//        [self.tableView beginUpdates];
//        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        // [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
//        [self.tableView endUpdates];
    }
}
- (void)kABCosDetailTCell:(KABCosDetailTCell *)cell imgViewTapped:(UIImageView *)imgView {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    KABProDetailImgItem *item = self.productModel.introduce_image_list[indexPath.row];
    KSPhotoItem *photoItem = [KSPhotoItem itemWithSourceView:imgView
                                                    imageUrl:[NSURL URLWithString:item.image_url]];
    [self showPhotoBrowser:@[photoItem] selectedIndex:0];
}

#pragma mark - GGBannerViewDelegate
- (void)imageView:(UIImageView *)imageView loadImageForUrl:(NSString *)url {
    [imageView yy_setImageWithURL:[NSURL URLWithString:url] placeholder:[KABDefaultVarModel sharedInstance].skinDefaultImg];
}
- (void)bannerView:(GGBannerView *)bannerView didSelectAtIndex:(NSUInteger)index {
    NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:self.productModel.detail_image_list.count];
    for (KABCosDetPubItem *item in self.productModel.detail_image_list) {
        KSPhotoItem *photoItem = [KSPhotoItem itemWithSourceView:bannerView
                                                      thumbImage:[KABDefaultVarModel sharedInstance].bigDefaultImg
                                                        imageUrl:[NSURL URLWithString:item.image_url]];
        [mArray addObject:photoItem];
    }
    [self showPhotoBrowser:mArray selectedIndex:index];
}

#pragma mark - event response
- (void)shopCartBarBtnTapped:(UIBarButtonItem *)barBtn {
    KABMallShopcartVC *vc = [[KABMallShopcartVC alloc] init];
    [self showViewController:vc sender:nil];
}
- (void)cmrServiceBtnTapped:(UIButton *)btn {
    //未登录是不能够聊天的
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    NSString * shopOwnerId = [NSString stringWithFormat:@"%zd", self.productModel.shop_owner_id];
    KABRCIMChatVC *chat = [[KABRCIMChatVC alloc] initWithConversationType:ConversationType_PRIVATE targetId:shopOwnerId];
    chat.title = self.productModel.shop_name;
    [self showViewController:chat sender:nil];
}
- (void)shopBtnTapped:(UIButton *)btn {
    KABMallMyShopVC *vc = [[KABMallMyShopVC alloc] init];
    vc.shop_owner_id = self.productModel.shop_owner_id;
    [self showViewController:vc sender:nil];
}
- (void)proColBtnTapped:(UIButton *)btn {
    self.productModel.is_collected = !self.productModel.is_collected;
    btn.selected = self.productModel.is_collected;
    
    [self requestProCollectWithProId:self.productModel.product_id isCollected:self.productModel.is_collected];
}
- (void)joinCartBtnTapped:(UIButton *)btn {
    KABMallBuyVC *vc = [[KABMallBuyVC alloc] init];
    vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    vc.proDetail = self.productModel;
    vc.completeBlock = ^() {
        [self requestAddShopCart];
    };
    [self presentViewController:vc animated:YES completion:nil];
}
- (void)buyBtnTapped:(UIButton *)btn {
    KABMallBuyVC *vc = [[KABMallBuyVC alloc] init];
    vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    vc.proDetail = self.productModel;
    vc.completeBlock = ^(){
        [self jumpToSureOrder];
    };
    [self presentViewController:vc animated:YES completion:nil];
}

#pragma mark - private methods
- (void)showPhotoBrowser:(NSArray<KSPhotoItem *> *)photoItems selectedIndex:(NSUInteger)index {
    KSPhotoBrowser *browser = [KSPhotoBrowser browserWithPhotoItems:photoItems selectedIndex:index];
    browser.dismissalStyle = KSPhotoBrowserInteractiveDismissalStyleNone;
    browser.backgroundStyle = KSPhotoBrowserBackgroundStyleBlack;
    browser.loadingStyle = KSPhotoBrowserImageLoadingStyleDeterminate;
    browser.pageindicatorStyle = KSPhotoBrowserPageIndicatorStyleDot;
    browser.bounces = NO;
    [browser showFromViewController:self];
}
- (void)jumpToSureOrder {
    KABMallSureOrderVC *vc = [[KABMallSureOrderVC alloc] init];
    vc.productArray = @[self.productModel];
    [self showViewController:vc sender:nil];
}

- (void)refreshWholeView {
    // 尾部加载更多的显示
    //    if (self.model.taskList.count >= self.model.totalCount) {
    //        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    //    } else {
    //        [self.tableView.mj_footer resetNoMoreData];
    //    }
    
    self.navigationItem.title = self.productModel.product_name;
    
    [self.hGGBannerView configBanner:self.productModel.bannerImgUrlArray];
    self.hPriceLabel.text = [NSString stringWithFormat:@"￥%.2f", self.productModel.selOriginalPrice / 100.0];
    self.hFeightLabel.text = [NSString stringWithFormat:@"运费：￥%.2f", self.productModel.freight / 100.0];
    
    self.proColBtn.selected = self.productModel.is_collected;
    
    [self.tableView reloadData];
}

#pragma mark - network request
- (void)requestProductDetail {
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
//    NSDictionary *pars = @{@"product_id" : @(self.proItem.productId)};
    
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    if (self.proItem) {
        [pars setObject:@(self.proItem.productId) forKey:@"product_id"];
    }else{
        [pars setObject:@(self.productId) forKey:@"product_id"];
    }
    
    if ([KABModel sharedInstance].isLogin) {
        [pars setObject:@([KABModel sharedInstance].userInfo.uid) forKey:@"visitor_id"];
        [pars setObject:[KABModel sharedInstance].userInfo.access_token forKey:@"access_token"];
    }
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiProduct] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求商品详情返回：%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            self.productModel = [KABMallProDetail yy_modelWithDictionary:responseObject[KABGlobalJsonKeyResult]];
            self.productModel.number = 1;
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求商品详情失败：%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestAddShopCart {
    // 加入购物车必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSDictionary *selPro = @{@"shop_id" : @(self.productModel.shop_id),
                             @"product_id" : @(self.productModel.product_id),
                             @"number" : @(self.productModel.number),
                             @"product_sku_id" : self.productModel.selSkuId};
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
//                           @"product_detail" : @[[self.productModel yy_modelToJSONObject]],
                           @"product_detail" : @[selPro]};
    NSLog(@"加入购物车的请求参数：%@", pars);
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiShoppingcart] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"加入购物车返回：%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
//            self.productModel = [KABMallProDetail yy_modelWithDictionary:responseObject[KABGlobalJsonKeyResult]];
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"已加入购物车"];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
//        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"加入购物车失败：%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestProCollectWithProId:(NSInteger)proId isCollected:(BOOL)isCollected {
    // 收藏必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    // 收藏请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"product_id" : @(proId),
                           @"is_collected" : isCollected ? @(1) : @(0)};
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiProductCollected] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"商品收藏返回：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            ;
        } else {
            self.productModel.is_collected = !isCollected;
            [self refreshWholeView];
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"商品收藏失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

#pragma mark - getters and setters

@end
